package orphaned;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.playcabbage.model.GridCellBean;
import net.playcabbage.utility.WebUtility;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class GridCellServlet extends HttpServlet {

	private WebUtility wu;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		wu = new WebUtility();
		
		PrintWriter out = resp.getWriter();
		out.print("Listing Grid cells...\n");

		try {
			getAsJSON(out,req);
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void getAsJSON(PrintWriter out,HttpServletRequest req) throws JSONException {
		Client client = Client.create();
		WebResource webResource = client.resource(wu.getCurrentDomain(req.getServerName()) + "/rest/gridcell/getjson");
		ClientResponse response = webResource.accept("application/json")
				.get(ClientResponse.class);
		if (response.getStatus() != 200) {
			throw new RuntimeException("Failed : HTTP error code : "
					+ response.getStatus());
		}

		JSONArray j = response.getEntity(JSONArray.class);

		List<GridCellBean> bl = new ArrayList<GridCellBean>();
		for (int x = 0; x < j.length();x++){
			JSONObject obj = j.getJSONObject(x);
			String json = obj.toString();
			Gson gson = new Gson();
			GridCellBean bean = gson.fromJson(json,GridCellBean.class);
			bl.add(bean);
		}

		for (int i = 0; i< j.length();i++){
			out.println("getGridcell_id: " + bl.get(i).getGridcell_id());
			out.println("getLocation_id(): " + bl.get(i).getLocation_id());
			out.println("getZ: " + bl.get(i).getZ());
			out.println("getY: " + bl.get(i).getY());
			out.println("getX: " + bl.get(i).getX());
			out.println("getLat: " + bl.get(i).getLat());
			out.println("getLat: " + bl.get(i).getLon());
			out.println("getCellcat: " + bl.get(i).getCellcat());
			out.println();
		}

	}

}